"use strict";
const babel = require("@babel/core");
const path = require("path");
const fs = require("fs");
const babelPlugin = path.resolve(__dirname, "plugin.js");
const request = require('request');
//读取cdn上版本文件
const fetchCdnFileData = (cdnFilePath) => {
  return new Promise((resolve, rejects) => {
    request(cdnFilePath, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        resolve(body)
      } else {
        rejects(error)
      }
    })
  })
}
// 获取cdn文件版本号记录
const fetchCdnVersion = async (cdnFilePath, mode) => {
  let res = ""
  if (mode === 'alpha' && cdnFilePath) {
    try {
      const cdnFileData = await fetchCdnFileData(cdnFilePath)
      let matchStr = cdnFileData.match(/alpha:\{versionRecord:\[(\S*)\]\},rc/)
      res = matchStr ? matchStr[1] : '';
    } catch (error) {
    }
  }
  console.log('远程版本号截取' + res);
  return res
}

const writeVersion = (recordFilePath, version, mode, cdnVersions) => {
  const newContent = babel.transformFileSync(recordFilePath, {
    plugins: [
      [babelPlugin, {
        version,
        mode,
        cdnVersions
      }]
    ],
  }).code;
  return newContent;
};

class UpdateRecord {
  constructor() {}
  static async apply({
    recordFilePath,
    version,
    mode,
    cdnFilePath
  }, callback) {
    const cdnVersions = await fetchCdnVersion(cdnFilePath, mode)
    const newContent = writeVersion(recordFilePath, version, mode, cdnVersions);
    fs.writeFileSync(recordFilePath, newContent.replace(/;/g, "") + '\n', "utf8");
    callback && callback()
  }
}
module.exports = UpdateRecord;